<?php

class Model_RoomZone
{
    /** Model_Table_RoomZone */
    protected $_table;


    /**
     * Retrieve table object
     * 
     * @return Model_Model_RoomZone_Table
     */
    public function getTable()
    {
        if (null === $this->_table) {
            // since the dbTable is not a library item but an application item,
            // we must require it to use it
            require_once APPLICATION_PATH . '/models/DbTable/RoomZone.php';
            $this->_table = new Model_DbTable_RoomZone;
        }
        return $this->_table;
    }

    /**
     * Save a new setting
     * 
     * @param  array $data 
     * @return int|string
     */
    public function save(array $data)
    {
        $table  = $this->getTable();
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);
            }
        }
        return $table->insert($data);
    }

    /**
     * Fetch all entries
     * 
     * @return Zend_Db_Table_Rowset_Abstract
     */
    public function fetchEntries()
    {
        // we are gonna return just an array of the data since
        // we are abstracting the datasource from the application,
        // at current, only our model will be aware of how to manipulate
        // the data source (dbTable).
        // This ALSO means that if you pass this model
        return $this->getTable()->fetchAll('1')->toArray();    
    }

    /**
     * Fetch an individual entry
     * 
     * @param  int|string $id 
     * @return null|Zend_Db_Table_Row_Abstract
     */
    public function fetchEntry($room_id)
    {
        $table = $this->getTable();
        $select = $table->select()->where('room_id = ?', $room_id);
        // see reasoning in fetchEntries() as to why we return only an array
        $rs =  $table->fetchRow($select)->toArray();
        $result = array();
        if (count($rs) > 0) { 
          // Assuming one zone_id here
            $result[] = $rs['zone_id'];
        }
        return $result;
    }
    

    /**
     * Update a new setpoint
     * 
     * @param  array $data 
     * @return int|string
     */
    public function update(array $data)
    {
        $table  = $this->getTable();
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);
            }
        }
        $room_id = $data["room_id"];
        $where = "room_id = $room_id";
        unset($data["room_id"]);
        return $table->update($data, $where);
    }

}